package Client.Dropbox.Communication

import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.remote.Node
import scala.actors.remote.RemoteActor._
import Client.Dropbox.Manager.BoxManager
import Client.Dropbox.Manager.FileManager
import Client.Dropbox.DropboxMain
import Client.Dropbox.Manager.ParentCommand
import Client.Dropbox.ServerCommands.ServerCommand
import Client.Dropbox.Manager.ParentBytesCommand
import Client.TaggingSystem.TagManager

/**
 * Remote Actor to receive updates from server
 * @param port the port with which the client connects to the server
 * @param peer the server
 */
class UpdateReciever (port: Int, peer: Node) extends Actor{
  /**
   * Acting method for actor
   */
  def act {
    //connect to server
    alive(port)
    register('Client, self)
    val user=FileManager.user
    val client=FileManager.client
    val updater = select (peer, 'Updater)
    //request first update from server
    updater ! (user, client)
    loop {
      //read update, call functions to handle it and request next one
      react {
        case "Done" => {
          println("Server: Done")
          exit
        }
        case ("deletedFile", name:String, parent:Long) => {
          println("Server: Deleted File "+name)
          DropboxMain.boxManager ! new ParentCommand (name, parent, ServerCommand.deletedFile)
          updater ! (user, client)
        }
        case ("newFolder", name:String, parent:Long, folder:Long) => {
          println("Server: New Folder "+name)
          DropboxMain.boxManager ! new ParentCommand (name, parent, ServerCommand.newFolder)
          updater ! (user, client)
        }
        case ("deletedFolder", name:String, parent:Long) => {
          println("Server: Deleted Folder "+name)
          DropboxMain.boxManager ! new ParentCommand (name, parent, ServerCommand.deletedFolder)
          updater ! (user, client)
        }
        case ("upload", name:String, parent:Long) => {
          println("Server: Upload file "+name)
          DropboxMain.boxManager ! new ParentCommand (name, parent, ServerCommand.upload)
          updater ! (user, client)
        }
        case ("newFile", name:String, parent:Long, bytes:Array[Byte]) => {
          println("Server: New File "+name)
          DropboxMain.boxManager ! new ParentBytesCommand (name, parent, bytes, ServerCommand.newFile)
          updater ! (user, client)
        }
        case ("changedFile", name:String, parent:Long, bytes:Array[Byte]) => {
          println("Server: Changed File "+name)
          DropboxMain.boxManager ! new ParentBytesCommand (name, parent, bytes, ServerCommand.changedFile)
          updater ! (user, client)
        }
        case ("change", tag:String) => {
          TagManager.init(tag)
        }
        case _ => 
      }
    }
    
  }

}